﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Citi.Helpers;

namespace Citi.ConsoleManager.ConsoleUi
{
    public class Program
    {
        static void Main(string[] args)
        {
            var xmlPath = ConfigurationManager.AppSettings["XmlPath"];
            var processes = XmlHelper.DeserializeFromXml<List<ProcessModel>>(Path.Combine(xmlPath, "Processes.xml"));

            foreach (var process in processes)
            {
                var processesRunning = Process.GetProcessesByName(process.Name).ToList();

                if (process.MustRun)
                {
                    if (processesRunning.Count == 0)
                        Process.Start(process.Path, process.Arguments);
                    else if (processesRunning.Count > 1)
                    {
                        processesRunning.RemoveAt(0);

                        foreach (var duplicatedProcess in processesRunning)
                            duplicatedProcess.Kill();
                    }
                }
                else
                {
                    foreach (var duplicatedProcess in processesRunning)
                        duplicatedProcess.Kill();
                }
            }
        }
    }
}
